package com.ndood.payment.core.oauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.social.security.SpringSocialConfigurer;

import com.ndood.payment.core.oauth.authorize.AuthorizeConfigManager;
import com.ndood.payment.core.oauth.handler.UnAuthenticatedAccessHandler;
import com.ndood.payment.core.oauth.handler.UnAuthorizedAccessHandler;

/**
 * oauth2资源服务器配置
 * 加了这个等于把app定义成资源服务器，访问资源的时候要先通过认证
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{
	
	@Autowired
	private SpringSocialConfigurer springSocialConfigurer;
	
	@Autowired
	private AuthorizeConfigManager authorizeConfigManager;
	
	@Autowired
	private UnAuthenticatedAccessHandler unAuthenticatedAccessHandler;

	@Autowired
	private UnAuthorizedAccessHandler unAuthorizedAccessHandler;

	/**
	 * 配置资源返回格式
	 */
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		super.configure(resources);
		resources
			.authenticationEntryPoint(unAuthenticatedAccessHandler)
			.accessDeniedHandler(unAuthorizedAccessHandler);
	}

	/**
	 * 配置http
	 */
	@Override
	public void configure(HttpSecurity http) throws Exception {
		
		http.apply(springSocialConfigurer)
		
		.and()
		.exceptionHandling()
		.authenticationEntryPoint(unAuthenticatedAccessHandler)
		.accessDeniedHandler(unAuthorizedAccessHandler)
		
		/*.and()
		.formLogin()
		.loginPage("/authentication/require")
		.loginProcessingUrl("/authentication/form")
		.successHandler(authenticationSuccessHandler)
		.failureHandler(authenticationFailureHandler)*/
		
		.and()
		.csrf().disable();
		
		// 调用公共的权限管理配置
		authorizeConfigManager.config(http.authorizeRequests());
		
	}
	
}
